package cn.sylinx.hbatis.ext.xmapper;

import java.util.List;
import java.util.Map;

import cn.sylinx.hbatis.db.cache.CacheQuery;
import cn.sylinx.hbatis.db.common.Record;
import cn.sylinx.hbatis.db.mapper.QueryMapper;
import cn.sylinx.hbatis.ext.parse.SqlParser;
import cn.sylinx.hbatis.ext.res.StatementHandler;
import cn.sylinx.hbatis.ext.xmapper.xml.QueryMapping;
import cn.sylinx.hbatis.ext.xmapper.xml.Sql;
import cn.sylinx.hbatis.ext.xmapper.xml.SqlForUse;
import cn.sylinx.hbatis.ext.xmapper.xml.XmlSqlMapper;
import cn.sylinx.hbatis.kit.StrKit;
import cn.sylinx.hbatis.kit.Tuple;

public class DefaultXmapperCacheQuery implements XmapperCacheQuery {

	private CacheQuery cacheQuery;

	public DefaultXmapperCacheQuery(CacheQuery cacheQuery) {
		this.cacheQuery = cacheQuery;
	}

	public <T> List<T> query(String sqlId, Map<String, Object> params) {

		String[] ids = sqlId.split("\\.");
		String namespaceId = ids[0];
		String id = ids[1];
		return query(namespaceId, id, params);
	}

	public Map<String, Object> queryFirstForMap(String namespaceId, String id, Map<String, Object> params) {

		if (!XmlSqlMapper.get().isInited()) {
			throw new RuntimeException("xmlSqlmapper plugin not started~");
		}

		Sql sql = XmlSqlMapper.get().getSqlBySqlId(namespaceId, id);

		String forUse = sql.getForUse();
		if (!SqlForUse.QUERY.getCode().equals(forUse)) {
			throw new IllegalArgumentException("sql is not query for use");
		}

		Tuple tp = getQueryStatement(sql.getStatement(), params);
		String st = (String) tp.get(0);
		Object[] pms = (Object[]) tp.get(1);

		return cacheQuery.queryFirstMap(st, pms);
	}

	public Map<String, Object> queryFirstForMap(String sqlId, Map<String, Object> params) {

		String[] ids = sqlId.split("\\.");
		String namespaceId = ids[0];
		String id = ids[1];

		return queryFirstForMap(namespaceId, id, params);
	}

	public List<Map<String, Object>> queryForMapList(String sqlId, Map<String, Object> params) {

		String[] ids = sqlId.split("\\.");
		String namespaceId = ids[0];
		String id = ids[1];

		return queryForMapList(namespaceId, id, params);
	}

	public List<Record> queryForRecords(String namespaceId, String id, Map<String, Object> params) {

		if (!XmlSqlMapper.get().isInited()) {
			throw new RuntimeException("xmlSqlmapper plugin not started~");
		}

		Sql sql = XmlSqlMapper.get().getSqlBySqlId(namespaceId, id);

		String forUse = sql.getForUse();
		if (!SqlForUse.QUERY.getCode().equals(forUse)) {
			throw new IllegalArgumentException("sql is not query for use");
		}

		Tuple tp = getQueryStatement(sql.getStatement(), params);
		String st = (String) tp.get(0);
		Object[] pms = (Object[]) tp.get(1);

		return cacheQuery.queryRecords(st, pms);
	}

	public List<Record> queryForRecords(String sqlId, Map<String, Object> params) {

		String[] ids = sqlId.split("\\.");
		String namespaceId = ids[0];
		String id = ids[1];

		return queryForRecords(namespaceId, id, params);
	}

	public Record queryFirstRecord(String namespaceId, String id, Map<String, Object> params) {

		if (!XmlSqlMapper.get().isInited()) {
			throw new RuntimeException("xmlSqlmapper plugin not started~");
		}

		Sql sql = XmlSqlMapper.get().getSqlBySqlId(namespaceId, id);

		String forUse = sql.getForUse();
		if (!SqlForUse.QUERY.getCode().equals(forUse)) {
			throw new IllegalArgumentException("sql is not query for use");
		}

		Tuple tp = getQueryStatement(sql.getStatement(), params);
		String st = (String) tp.get(0);
		Object[] pms = (Object[]) tp.get(1);

		return cacheQuery.queryFirstRecord(st, pms);
	}

	public Record queryFirstRecord(String sqlId, Map<String, Object> params) {

		String[] ids = sqlId.split("\\.");
		String namespaceId = ids[0];
		String id = ids[1];

		return queryFirstRecord(namespaceId, id, params);
	}

	public List<Object[]> queryObjectArrayList(String namespaceId, String id, Map<String, Object> params) {

		if (!XmlSqlMapper.get().isInited()) {
			throw new RuntimeException("xmlSqlmapper plugin not started~");
		}

		Sql sql = XmlSqlMapper.get().getSqlBySqlId(namespaceId, id);

		String forUse = sql.getForUse();
		if (!SqlForUse.QUERY.getCode().equals(forUse)) {
			throw new IllegalArgumentException("sql is not query for use");
		}

		Tuple tp = getQueryStatement(sql.getStatement(), params);
		String st = (String) tp.get(0);
		Object[] pms = (Object[]) tp.get(1);

		return cacheQuery.query(st, pms);
	}

	public List<Object[]> queryObjectArrayList(String sqlId, Map<String, Object> params) {

		String[] ids = sqlId.split("\\.");
		String namespaceId = ids[0];
		String id = ids[1];

		return queryObjectArrayList(namespaceId, id, params);
	}

	/**
	 * 带有StatementHandler
	 * 
	 * @param statement
	 * @param params
	 * @return
	 */
	private Tuple getQueryStatement(String statement, Map<String, Object> params) {

		StatementHandler sqlHandler = null;
		if (params != null) {
			Object obj = params.get(StatementHandler.class.getName());
			if (obj != null && (obj instanceof StatementHandler)) {
				sqlHandler = (StatementHandler) obj;
			}
		}
		return SqlParser.parseSql(statement, params, sqlHandler);
	}

	public Object[] queryFirstObjectArray(String namespaceId, String id, Map<String, Object> params) {

		if (!XmlSqlMapper.get().isInited()) {
			throw new RuntimeException("xmlSqlmapper plugin not started~");
		}

		Sql sql = XmlSqlMapper.get().getSqlBySqlId(namespaceId, id);

		String forUse = sql.getForUse();
		if (!SqlForUse.QUERY.getCode().equals(forUse)) {
			throw new IllegalArgumentException("sql is not query for use");
		}

		Tuple tp = getQueryStatement(sql.getStatement(), params);
		String st = (String) tp.get(0);
		Object[] pms = (Object[]) tp.get(1);

		return cacheQuery.queryFirst(st, pms);
	}

	public Object[] queryFirstObjectArray(String sqlId, Map<String, Object> params) {

		String[] ids = sqlId.split("\\.");
		String namespaceId = ids[0];
		String id = ids[1];

		return queryFirstObjectArray(namespaceId, id, params);
	}

	@Override
	public List<Map<String, Object>> queryForMapList(String namespaceId, String id, Map<String, Object> params) {

		if (!XmlSqlMapper.get().isInited()) {
			throw new RuntimeException("xmlSqlmapper plugin not started~");
		}

		Sql sql = XmlSqlMapper.get().getSqlBySqlId(namespaceId, id);

		String forUse = sql.getForUse();
		if (!SqlForUse.QUERY.getCode().equals(forUse)) {
			throw new IllegalArgumentException("sql is not query for use");
		}

		Tuple tp = getQueryStatement(sql.getStatement(), params);
		String st = (String) tp.get(0);
		Object[] pms = (Object[]) tp.get(1);

		return cacheQuery.queryMap(st, pms);
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> query(String namespaceId, String id, Map<String, Object> params) {

		if (!XmlSqlMapper.get().isInited()) {
			throw new RuntimeException("xmlSqlmapper plugin not started~");
		}

		Sql sql = XmlSqlMapper.get().getSqlBySqlId(namespaceId, id);

		String forUse = sql.getForUse();
		if (!SqlForUse.QUERY.getCode().equals(forUse)) {
			throw new IllegalArgumentException("sql is not query for use");
		}

		Tuple tp = getQueryStatement(sql.getStatement(), params);
		String st = (String) tp.get(0);
		Object[] pms = (Object[]) tp.get(1);

		final QueryMapping qm = sql.getQueryMapping();
		QueryMapper<T> qmapper = null;

		if (qm != null) {
			qmapper = new QueryMapper<T>() {

				@Override
				public Map<String, String> getJdbcToJavaMapper() {
					return qm.getMap();
				}

				@Override
				public Class<T> getValueObjectClass() {

					try {
						String clzStr = qm.getReturnClass();
						if (StrKit.isNotBlank(clzStr)) {
							return (Class<T>) Class.forName(clzStr);
						}
						return null;
					} catch (Exception e) {
						return null;
					}

				}
			};
		}

		return cacheQuery.query(st, qmapper, pms);
	}

	public <T> T queryFirst(String sqlId, Map<String, Object> params) {

		List<T> list = query(sqlId, params);

		return list != null && !list.isEmpty() ? list.get(0) : null;
	}

	@SuppressWarnings("unchecked")
	public <T> T queryFirst(String namespaceId, String id, Map<String, Object> params) {

		if (!XmlSqlMapper.get().isInited()) {
			throw new RuntimeException("xmlSqlmapper plugin not started~");
		}

		Sql sql = XmlSqlMapper.get().getSqlBySqlId(namespaceId, id);

		String forUse = sql.getForUse();
		if (!SqlForUse.QUERY.getCode().equals(forUse)) {
			throw new IllegalArgumentException("sql is not query for use");
		}

		final QueryMapping qm = sql.getQueryMapping();
		Tuple tp = getQueryStatement(sql.getStatement(), params);
		String st = (String) tp.get(0);
		Object[] pms = (Object[]) tp.get(1);

		QueryMapper<T> qmapper = null;

		if (qm != null) {
			qmapper = new QueryMapper<T>() {

				@Override
				public Map<String, String> getJdbcToJavaMapper() {
					return qm.getMap();
				}

				@Override
				public Class<T> getValueObjectClass() {

					try {
						String clzStr = qm.getReturnClass();
						if (StrKit.isNotBlank(clzStr)) {
							return (Class<T>) Class.forName(clzStr);
						}
						return null;
					} catch (Exception e) {
						return null;
					}

				}
			};
		}

		return cacheQuery.queryFirst(st, qmapper, pms);
	}

}
